<template>
  <div>
    <el-dialog :visible.sync="dialogFormVisible" title="添加章节">
      <el-form>
        <el-form-item :label-width="formLabelWidth" label="章节标题">
          <el-input v-model="chapter.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="章节排序">
          <el-input-number v-model="chapter.sort" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import chapterApi from '@/api/chapter'
export default {
  data() {
    return {
      chapter: {
        sort: 0
      },
      chapters: [],
      formLabelWidth: '120px',
      dialogFormVisible: false
    }
  },
  methods: {
    handleSubmit() {
      // 必须在新增章之前 将它所属的课程id设置给他
      this.chapter.courseId = this.$parent.$parent.courseId
      if (this.chapter.id) {
        this.update()
      } else {
        this.save()
      }
    },
    save() {
      chapterApi.saveChapter(this.chapter).then(res => {
        this.$message.success('新增章成功')
        this.dialogFormVisible = false
        this.resetForm()
        // 刷新列表
        this.$parent.getChapters()
      })
    },
    update() {
      chapterApi.updateChapter(this.chapter).then(res => {
        this.$message.success(res.message)
        this.dialogFormVisible = false
        this.resetForm()
        // 刷新列表
        this.$parent.getChapters()
      })
    },
    // 重置表单
    resetForm() {
      this.chapter = {
        sort: 0
      }
    }
  }
}
</script>
